<template>
  <div class="page-container">
    <el-card shadow="never">
      <div style="margin-bottom: 20px;">
        <el-button type="primary" @click="handleAdd">新增用户</el-button>
        <!-- 预留：挂角色按钮 -->
        <el-button type="success" @click="assignRoles(null)">批量分配角色</el-button>
      </div>

      <!-- 用户表格 -->
      <el-table :data="tableData" border stripe style="width: 100%" v-loading="loading">
        <el-table-column align="center" prop="username" label="用户名"/>
        <el-table-column align="center" prop="realName" label="真实姓名"/>
        <el-table-column align="center" prop="phone" label="手机号"/>
        <el-table-column align="center" prop="email" label="邮箱"/>
        <el-table-column align="center" label="状态">
          <template #default="{ row }">
            <el-tag v-if="row.enabled === 1" type="success">启用</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="300">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
            <el-button size="small" type="warning" @click="assignRoles(row.id)">分配角色</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 20px; text-align: right">
        <el-pagination
            background
            layout="total, prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="form.id ? '编辑用户' : '新增用户'" v-model="showDialog" width="50%">
      <el-form :model="form" label-width="90px" ref="formRef" :rules="rules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="新增时必填，编辑可不填"/>
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="form.realName" placeholder="请输入真实姓名"/>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="form.phone" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="form.email" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.enabled">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>

  <SelectorDialog
      v-model="selectorVisible"
      :data="allRoles"
      :selected="selectedRoleIds"
      title="选择角色"
      label-prop="name"
      key-prop="id"
      @confirm="handleAssignRolesConfirm"
  />
</template>

<script setup>
import {onMounted, ref} from 'vue';
import request from '@/api/request';
import {ElMessage, ElMessageBox} from "element-plus";
import SelectorDialog from "@/components/SelectorDialog";

// 表格 & 分页
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);

// 弹窗与表单
const showDialog = ref(false);
const formRef = ref();
const form = ref({
  id: null,
  username: '',
  password: '',
  realName: '',
  phone: '',
  email: '',
  enabled: 1
});

// 校验规则
const rules = {
  username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
  password: [{required: false, min: 6, message: '密码不少于6位', trigger: 'blur'}]
};

// 获取列表
const fetchData = () => {
  loading.value = true;
  request.get('/sys-user/page', {
    params: {page: currentPage.value, size: pageSize.value}
  }).then(res => {
    const data = res.data.data;
    tableData.value = data.records;
    total.value = data.total;
  }).finally(() => {
    loading.value = false;
  });
};

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchData();
};

// 添加
const handleAdd = () => {
  form.value = {
    id: null,
    username: '',
    password: '',
    realName: '',
    phone: '',
    email: '',
    enabled: 1
  };
  showDialog.value = true;
};

// 编辑
const handleEdit = (row) => {
  form.value = {...row};
  form.value.password = ''; // 不回显密码
  showDialog.value = true;
};

// 删除
const handleDelete = (id) => {
  ElMessageBox.confirm('确定删除该用户吗？', '提示', {
    type: 'warning'
  }).then(() => {
    request.delete(`/sys-user/${id}`).then(() => {
      ElMessage.success('删除成功');
      fetchData();
    });
  }).catch(() => {
  });
};

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (!valid) return;

    const api = form.value.id ? request.put : request.post;
    const url = '/sys-user';

    api(url, form.value).then(() => {
      ElMessage.success(`${form.value.id ? '更新' : '添加'}成功`);
      showDialog.value = false;
      fetchData();
    });
  });
};

// 控制选择器弹窗
const selectorVisible = ref(false);
const allRoles = ref([]);
const selectedRoleIds = ref([]);

// 加载所有角色
const loadAllRoles = async () => {
  const res = await request.get('/sys-role');
  allRoles.value = res.data.data || [];
};

// 获取某个用户的当前角色
const loadUserRoles = async (userId) => {
  if (!userId) {
    selectedRoleIds.value = [];
    return;
  }
  const res = await request.get(`/sys-user-role/user/${userId}`);
  selectedRoleIds.value = res.data.data || [];
};

// 打开分配角色弹窗
const assignRoles = async (userId) => {
  await loadAllRoles(); // 每次打开都刷新角色列表
  const isBatch = userId === null;
  if (isBatch) {
    ElMessage.warning("暂不支持批量分配");
    return;
  }

  await loadUserRoles(userId);
  currentUserId.value = userId;
  selectorVisible.value = true;
};

// 当前操作的用户ID
const currentUserId = ref(null);

// 提交分配角色
const handleAssignRolesConfirm = (roleIds) => {
  const dto = {
    userId: currentUserId.value,
    roleIds
  };

  request.post('/sys-user-role/assign', dto).then(() => {
    ElMessage.success('角色分配成功');
    fetchData(); // 刷新用户列表
  }).catch(() => {
  });
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
